﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Build.Framework;

namespace MSBuild.DotNetNuke.Tasks
{
    /// <summary>
    /// Creates/replaces the script component in the manifest file based on the list of files
    /// passed.
    /// </summary>
    public class ScriptComponent : Component
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ScriptComponent"/> class.
        /// </summary>
        public ScriptComponent()
        {
            _type = ComponentType.Script;
        }


        protected override string GetContainerElement()
        {
            return "scripts";
        }

        protected override void WriteItemElement(XmlWriter output, ITaskItem item)
        {
            string scriptName = System.IO.Path.GetFileName(item.ItemSpec);
            string scriptType = GetScriptType(scriptName);
            string scriptVersion = "";

            output.WriteStartElement("script");
            output.WriteAttributeString("type", scriptType);

            if (!string.IsNullOrEmpty(Path))
            {
                output.WriteElementString("path", Path);
            }
            output.WriteElementString("name", scriptName);
            if (scriptType == "Install")
            {
                scriptVersion = GetVersion(item);
                output.WriteElementString("version", scriptVersion);
            }

            output.WriteEndElement(); // </script>

            if (scriptType == "Install")
                Log.LogMessage(MessageImportance.Low, string.Format("{0} Script: {1} - Version: {2}",
                        scriptType, scriptName, scriptVersion));
            else
                Log.LogMessage(MessageImportance.Low, string.Format("{0} Script: {1}",
                        scriptType, scriptName));
        }

        private string GetVersion(ITaskItem item)
        {
            return System.IO.Path.GetFileNameWithoutExtension(item.ItemSpec);
        }

        private string GetScriptType(string scriptName)
        {
            if (scriptName.ToLower().StartsWith("uninstall."))
                return "Uninstall";
            else
                return "Install";
        }
    }
}
